let pageData = {
    "records": [
        {
            "role": {
                "id": 2,
                "name": "普通用户",
                "perms": null
            },
            "perm": {
                "id": 1,
                "name": "访问管理页面",
                "url": "/admin.html/*"
            }
        },
        {
            "role": {
                "id": 4,
                "name": "管理员",
                "perms": null
            },
            "perm": {
                "id": 1,
                "name": "访问管理页面",
                "url": "/admin.html/*"
            }
        },
        {
            "role": {
                "id": 4,
                "name": "管理员",
                "perms": null
            },
            "perm": {
                "id": 2,
                "name": "角色权限管理",
                "url": "/role/perm/*"
            }
        },
        {
            "role": {
                "id": 4,
                "name": "管理员",
                "perms": null
            },
            "perm": {
                "id": 3,
                "name": "查询角色权限",
                "url": "/role/perm/query"
            }
        },
        {
            "role": {
                "id": 4,
                "name": "管理员",
                "perms": null
            },
            "perm": {
                "id": 4,
                "name": "查询用户角色",
                "url": "/role/select*"
            }
        }
    ],
    "total": 5,
    "size": 5,
    "current": 1,
    "orders": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 1,
    "prePage": 1,
    "nextPage": 1,
    "startPage": 1,
    "endPage": 1
}
let $entry_role = $('#admin-card-perm-list-entry')
let $entry_pages = $('#admin-card-perm-pages-entry')
function renderPerms(perms, delay){
    $entry_role.html('')
    setTimeout(function (){
        perms.forEach(function (perm){
            let fn_modify = "renderPermEditModal(this," + perm['id'] + ")"
            let fn_remove = "removePerm(" + perm['id'] + ")"

            $entry_role.append(`
            <tr valign="baseline">
                <td><input type="checkbox" class="cb_perm" data-pid=${perm['id']} style="width: 20px; height: 20px;"></td>
                <td>${perm['id']}</td>
                <td>${perm['name']}</td>
                <td>${perm['url']}</td>
                <td>
                     <button class="btn btn-primary" onclick="${fn_modify}" data-bs-toggle="modal" data-bs-target="#modal-edit-perm">
                         <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
                          <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
                          <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
                        </svg>
                        编辑
                     </button>
                     <button class="btn btn-danger" onclick="${fn_remove}">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-lg" viewBox="0 0 16 16">
                          <path d="M2.146 2.854a.5.5 0 1 1 .708-.708L8 7.293l5.146-5.147a.5.5 0 0 1 .708.708L8.707 8l5.147 5.146a.5.5 0 0 1-.708.708L8 8.707l-5.146 5.147a.5.5 0 0 1-.708-.708L7.293 8 2.146 2.854Z"/>
                        </svg>
                        删除
                     </button>
                </td>
          </tr>
        `)})
    }, delay)
}
// 编辑某个权限时渲染修改的模态框
function renderPermEditModal(btn, permId){
    renderModal(btn, ajaxPostJSON('/perm/select/' + permId))
}
// 渲染新增角色
function renderModalInsertRole(){
    let $role = $("select[name='roleExtendsId']")
    $role.html('')
    // 获取所有的角色并渲染
    ajaxPostJSON('/role/selectall').forEach(function (role){
        $role.append(`<option value="${role['id']}">${role['name']}</option>`)
    })
    $role.prepend(`<option value="0">无</option>`)
}
// 渲染新增角色的权限
function renderModalInsertRolePerm(){
    let $selectRole =$("select[name='roleId']")
    let $selectPerm = $("select[name='permId']")
    $selectRole.html('')
    $selectPerm.html(`<option value="">请先选择角色</option>`)
    // 渲染所有的角色ID
    ajaxPostJSON('/role/selectall').forEach(function (role) {
        $selectRole.append(`<option value="${role['id']}">${role['name']}</option>`)
    })
    // 监听变化
    $selectRole.on('change', function (){
        // 查看当前角色所有的权限
        $('#form-role-perm').html('')
        let perms = new Set()
        ajaxPostJSON('/role/perm/select/' + $(this).val()).forEach(function (perm){
            $('#form-role-perm').append(`<li class="list-group-item mt-3">${perm['id']}: ${perm['name']}</li>`)
            perms.add(perm['id'])
        })
        // 渲染当前用户没有的权限ID
        $selectPerm.html('')
        ajaxPostJSON('/role/perm/selectall').forEach(function (perm){
            if(!perms.has(perm['id']))
                $selectPerm.append(`<option value="${perm['id']}">${perm['id']}: ${perm['name']}</option>`)
        })
    })
    // 给添加按钮设置监听
    $('#modal-btn-insert-perm').click(function (){
        addRolePerm($selectRole.val(), $selectPerm.val())
    })
}
function renderPage(page){
    $entry_pages.html('')
    let $perPage = $(`<li></li>`)
    // 渲染尾部
    let $tail = `<li class="align-self-center r">
                &nbsp;&nbsp;到第&nbsp;&nbsp;
            </li>
            <li class="align-self-center">
                <input id="admin-user-input-to-page" class="input-group" name="pageNum" size="5">
            </li>
            <li class="align-self-center">
                &nbsp;页&nbsp;
            </li>
            <li class="align-self-center">
                <button class="btn btn-outline-dark" onclick="toPage('admin-user-input-to-page', 1, ${page.pages})">确定</button>
            </li>`

    // 计算页数的渲染范围
    page.prePage = Math.max(1, page['current']- 1)
    page.nextPage = Math.min(page['pages'], page['current'] + 1)
    page.startPage = Math.max(1, page['current'] - 2)
    page.endPage = Math.min(page['pages'], page['current'] + 2)
    // 渲染每一页
    for (let i = page.startPage; i <= page.endPage; i++) {
        if(i === page.current){ // 渲染当前页，设置一个高亮的效果
            $perPage.append(`
            <li class="page-item mx-2 active" aria-current="page">
             <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
         </li>`)
        } else {
            $perPage.append(`
             <li class="page-item mx-2" aria-current="page">
                 <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
             </li>`
            )
        }
    }
    $entry_pages.html('')
    $entry_pages.html(`
            <ul class="pagination mx-auto justify-content-center">
            <li class="align-self-center me-3 rounded-3">
                    第 ${page.current} 页 &nbsp;&nbsp; 共 ${page.pages} 页
            </li>
            <li class="page-item ms-page">
                 <a class="page-link" href="${paramUpdateCurrentParam('pageNum', 1)}">
                    首页
                 </a>
            </li>
            <!--上一页-->
           <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.prePage)}">上一页</a>
            </li>`
        + $perPage.html() + `
            <!--下一页-->
             <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.nextPage)}">下一页</a>
            </li>
            <!--最后一页-->
             <li class="page-item ms-page" href="/index.html?pageNum=${page.pages}">
                  <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.pages)}">末页</a>
             </li>` + $tail +
        `</ul>`)
    $('#textShowResult').text('共 ' + page.total + ' 条结果')

}
////////////////////// 功能函数区
///// 跳转到指定页
function toPage(inputId, mini, maxi){
    $input = $('#' + inputId)
    let page = $input.val()
    // 限制页面的范围
    page = Math.min(page, maxi)
    page = Math.max(page, mini)
    location.href = paramUpdateCurrentParam('pageNum', page)
}
///// 搜索
function searchProvider(btn){
    location.href = paramUpdateCurrentParam('name', $(btn).prev('input').val())
}

// 保存权限
function savePerm(form){
    let $form = $(form)
    let result = ajaxPostUpdate({
        'url': '/perm/update',
        'data': $form.serialize()
    })
    if(result['code'] === CODE_SUCCESS)
        ms_show_toast_callback(true, result['msg'], function (){
            location.reload()
        })
    else
        ms_show_toast(false, result['msg'])
}
///// 删除供应商
function removeProvider(id){
    let result = ajax('DELETE', '/role/delete/' + id)
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_callback(true, result['msg'], function (){
            location.reload()
        })
    } else
        ms_show_toast(false, result['msg'])
}
// 删除多个供应商
function removeProviders(){
    ids = []
    // 获取选择的需要删除的供应商
    $('.cb_role').each(function (){
        if($(this).prop('checked') === true){
            ids.push($(this).data('id'))
        }
    })
    if(ids.length === 0) { ms_show_toast(false, '请选择要删除的供应商') ; return }
    let result = ajax('DELETE', '/role/delete/' + ids)
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_callback(true, result['msg'], function (){
            location.reload()
        })
    } else
        ms_show_toast(false, result['msg'])
}
// 添加供应商
function insertProvider(){
    let $form = $('#form-insert')
    let result = ajaxPostJSONByMap('/role/insert', $form.serialize())
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    }
    ms_show_toast(false, result['msg'])
}
// 搜索角色权限
function searchUserPerm(btn){
    let $input = $(btn).prev('input')
    let searchKey = $input.prev('select').val()
    let searchVal = $input.val()
    location.href = paramUpdateCurrentParam(searchKey, searchVal)
}
function addRolePerm(roleId, permId){
    let result = ajaxCustom('POST', {
        url: '/role/perm/insert',
        data: {'roleId' : roleId, 'permId': permId}
    })
    if(result.code === CODE_SUCCESS) {
        ms_show_toast_callback(true, result['msg'], function (){
            renderModalInsertRolePerm()
            // 重新选择当前的角色
            $("select[name='roleId']").val(roleId).change()
        })
    }
    else
        ms_show_toast(false, result['msg'])
}
// 删除单个权限
function removePerm(permId){
    if(!confirm("是否确认这条权限? " )) return
    let result = ajaxDelete({
        url: '/perm/delete/' + permId
    })
    if(result.code === CODE_SUCCESS)
        ms_show_toast_reload(true, result['msg'])
    else
        ms_show_toast(false, result['msg'])
}
// 删除多个权限
function removePerms(){
    let permIds = []
    // 获取选择的需要删除的供应商
    $('.cb_perm').each(function (){
        if($(this).prop('checked') === true){
            permIds.push($(this).data('pid'))
        }
    })
    if(permIds.length === 0) { ms_show_toast(false, '请选择需要删除的角色权限') ;return }
    if(!confirm("是否确认删除这些权限 ? ")) return
    let result = ajaxDelete({
        url: '/perm/delete/' + permIds,
    })
    if(result.code === CODE_SUCCESS)
        ms_show_toast_reload(true, result['msg'])
    else
        ms_show_toast(false, result['msg'])
}
// 添加角色
function insertPerm(formId){
    let $form = $(formId)
    let result = ajaxPostJSONByMap('/perm/insert', $form.serialize())
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
// 删除角色
function deleteRole(roleId){
    if(!confirm("确认要删除角色吗？这会导致拥有该角色的用户变为[普通会员]的身份")) return
    let result = ajaxDelete({
        'url': '/role/delete/'+ roleId
    })
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
// 全选
$('#cb_all').click(function (){
    $('.cb_perm').prop('checked', $(this).prop('checked'))
})
$(document).ready(function (){
    pageData = ajaxPostJsonByCurrentUrlParam('/perm/select')
    console.log(pageData)
    renderPerms(pageData['records'], 100)
    renderPage(pageData)
})